package com.chen.stopwatch.sound;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class SoundManager {
	static final int MAX_STREAMS = 2;

	static final int STREAM_TYPE = AudioManager.STREAM_MUSIC;// STREAM_MUSIC in
																// AudioManager

	static final int SRC_QUALITY = 0;

	static SoundManager _sSoundManager = null;

	SoundPool _soundPool = null;

	public static SoundManager instance() {
		if (null == _sSoundManager) {
			_sSoundManager = new SoundManager(MAX_STREAMS, STREAM_TYPE,
				SRC_QUALITY);
		}
		return _sSoundManager;
	}

	protected SoundManager(int maxStreams, int streamType, int srcQuality) {
		_soundPool = new SoundPool(maxStreams, streamType, srcQuality);
	}

	public int load(Context context, int resId) {
		if (null == context)
			return 0;
		return _soundPool.load(context, resId, 1);
	}

	/**
	 * @param soundID
	 *            Id of res stored in raw.
	 * @param priority
	 *            Stream priority (0 = lowest priority)
	 * @param loop
	 *            loop mode (0 = no loop, -1 = loop forever)
	 * @param rate
	 *            playback rate (1.0 = normal playback, range 0.5 to 2.0)
	 * 
	 * @return 0 == failed, other == streamId.
	 */
	public int play(Context context, int soundId, int priority, int loop,
			float rate) {
		if (null == context)
			return 0;
		// int soundId = _soundPool.load(context, resId, 1);

		// Utils.logDebug("test", "SoundId = " + soundId);
		AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		float currentSound = am.getStreamVolume(AudioManager.STREAM_MUSIC);
		float maxSound = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		float volume = currentSound / maxSound;

		return _soundPool.play(soundId, volume, volume, priority, loop, rate);
	}

	/**
	 * @param streamID
	 *            returned by play()
	 */
	public void pause(int streamID) {
		_soundPool.pause(streamID);
	}

	public void resume(int streamID) {
		_soundPool.resume(streamID);
	}

	public void stop(int streamID) {
		_soundPool.stop(streamID);
	}

	protected void internal_destroy() {
		if (null != _soundPool) {
			_soundPool.release();
			_soundPool = null;
		}
	}

	public static void destroy() {
		if (null != _sSoundManager) {
			_sSoundManager.internal_destroy();
			_sSoundManager = null;
		}
	}
}
